import { createStore } from 'vuex'
import { ElMessageBox } from 'element-plus'
import request from '@/utils/request';

// 创建一个新的 store 实例
export default createStore({
  state () {
    return {
      currentUser_save: undefined,
      menu:[],
      log: {
        string: '', /* 日志返回内容的字符串 */
        checkedLog: {}, /* 日志对象 */
        logData: [],  /* 日志的返回内容 */
      },
      /* 连接的服务器信息 */
      destHostParam:{

      }
    }
  },
  getters:{
    currentUser(state){
      if(!state.currentUser_save){
          return JSON.parse(localStorage.getItem('currentUser'))
      }else{
          return state.currentUser_save
      }
    },
  },
  mutations: {
    LOGIN (state, user) {
      state.currentUser_save = user
      localStorage.setItem('currentUser', JSON.stringify(user))
      console.log("12")
    },
    LOGOUT (state) {
      state.currentUser_save = undefined
    },
    /* 向服务器发出请求，获取菜单信息并赋值给menu */
    GetMenu(state){
      state.menu = [
        {
          label: '首页',
          route: '/user/info',
          children:[]
        },
        {
          label: '修改密码',
          route: '/user/change',
          children:[]
        },
        {
          label: '系统管理',
          route: '',
          children:[
              {
                label: '用户管理',
                route: '/user/userManage',
                children:[]
              },
              {
                label: '角色管理',
                route: '/user/permissionManage',
                children:[]
              },
              {
                label: '菜单管理',
                route: '/user/menuManage',
                children:[]
              },
              {
                label: '会话管理',
                route: '/user/sessionManage',
                children:[]
              },
              {
                label: '日志管理',
                route: '/user/logManage',
                children:[]
              },
            ]
        },
        {
            label: '系统工具',
            route: '',
            children:[
                {
                  label: '远程终端',
                  route: '/user/remoteTerminal',
                  children:[]
                },
            ]
        },
      ]
    },
    /* 注销/删除账号 */
    DeleteUser(state,data){
      let idList = []
      data.userList.forEach(u => {
        idList.push(u.userId)
      });
      request.post("/api/start/delete", idList).then(res => {
        if (res.code === 200) {
          data.vm.$message({
            message: '成功删除账号',
            type: 'success'
          });
          location.reload()
          /* data.vm.$router.push('/login') */
        } else {
          data.vm.$message({
            message: res.msg,
            type: 'error'
          });
        }
      })
    },
    /* 设置查看的日志 */
    SetLog(state, data){
      state.log.checkedLog = data.log

      let id = state.log.checkedLog.id
      request.get("newapi/diary/log",{
        params: {
          id
        }
      }).then(
        res => { 
          if(res.code == 200){
              state.log.logData = res.data

              state.log.string = ''
              state.log.logData.forEach(l => {
                state.log.string += l + '\n'
              });

          }else{
            console.log(res.msg);
          }
        },
        error => { 
          console.log(error.message);
        },
      )
    },
    /* 连接服务器终端 */
    LinkHost(state, data){
      request.post("newapi/host/connect",{
        host: data.hostInfo.host,
        hostName: data.hostInfo.hostName,
        id: data.hostInfo.id,
        password: data.hostInfo.password,
        port: data.hostInfo.port,
        userId: 0,
        username: data.hostInfo.username
      }).then(
        res => { 
          if(res.code == 200){
            data.vm.$message({
              message:'连接成功！',
              type: 'success'
            })
            state.destHostParam = data.hostInfo
            data.vm.$router.push('/user/remoteTerminal')
          }else{
            data.vm.$message({
              message: res.msg,
              type: 'error'
            })
          }
        },
        error => { 
          data.vm.$message({
            message: error.message,
            type: 'error'
          })
        },
      )
    },
    GetAuthTable(state){
      request.get("newapi/role/list", {params:{
        pageSize: 9999,
        pageNum: 1,
      }}).then(
        res => { 
          if(res.code == 200){
            state.authTable = res.data.records
          }else{
            console.log(res.msg);
          }
        },
        error => { 
          console.log(error.message);
        },
      )
    }
  },
  actions:{
      login (content, user) {
        content.commit("LOGIN", user)
      },
      logOut (content) {
        content.commit("LOGOUT")
      },
      /* 获取菜单信息 */
      getMenu(content){
        content.commit("GetMenu")
      },
      /* 注销/删除账号 */
      deleteUser(content, data){
        ElMessageBox.confirm(
          '您正在 注销/删除 账号，这将意味着这些账号的所有信息会在我们的服务器上消失，这个操作不可挽回，确认要继续吗?',
          '警告',
          {
            confirmButtonText: '继续',
            cancelButtonText: '算了吧',
            type: 'warning',
          }
        ).then(() => {
            /* 确认后删除账号 */
            content.commit("DeleteUser", data)
          }).catch(() => {
          data.vm.$message({
            message: '注销已取消',
            type: 'info'
          });
        })
      },
      /* 设置查看的日志 */
      setLog(content, data){
        content.commit('SetLog', data)
      },
      /* 连接会话 */
      linkHost(content, data){
        content.commit('LinkHost', data)
      }
  }
})